package com.boot.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.boot.common.to.es.SkuEsModel;
import com.boot.mall.search.config.ElasticSearchConfig;
import com.boot.mall.search.constant.EsConstant;
import com.boot.mall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构造保存请求，指定存储的索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //指定数据的ID为skuID
            indexRequest.id(skuEsModel.getSkuId().toString());
            //将sku信息转换为JSON数据并添加到保存请求中
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //执行保存
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.getCommonOptions());
        boolean b = bulk.hasFailures();
        if (b){
            BulkItemResponse[] items = bulk.getItems();
            for (BulkItemResponse item : items) {
                System.out.println("成功上架商品ID为：" + item.getId());
            }
            return false;
        }
        return true;
    }
}
